<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入用户名搜索"
                    v-model="searchUser"
                    clearable
                    @clear="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="phoneNum"></el-table-column>
        <el-table-column label="需求数" prop="demandNum"></el-table-column>
        <el-table-column label="简介" prop="introduction"></el-table-column>
        <el-table-column label="状态" prop="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :inactive-value=0
              :active-value=1
              @change="changeUserStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" style="display: inline-block;" width="190px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改用户信息" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.userId)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" @click="deleteUser(scope.row.userId)"
                         size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitAddUser">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="editForm.username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="editForm.name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="editForm.email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="editForm.phoneNum">
          <el-input v-model="editForm.phoneNum"></el-input>
        </el-form-item>
        <el-form-item label="需求数" prop="editForm.demandNum">
          <el-input v-model="editForm.demandNum"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="editForm.introduction">
          <el-input v-model="editForm.introduction"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="changeUser(editForm)">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
    import {
        addUser,
        changeUserById,
        deleteUserById,
        selectAllUser,
        selectUser
    } from "../../assets/api/userApi";

    export default {
        name:'user',
        data() {
            let checkEmail = (rule, value, cb) => {
                const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
                if(regEmail.test(value)) {
                    return cb()
                }
                cb(new Error('请输入合法的邮箱'))
            };
            let checkPhoneNum = (rule, value, cb) =>{
                const regPhone = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

                if(regPhone.test(value)) {
                    return cb()
                }
                cb(new Error('请输入合法的手机号'))
            };
            return {
                userList: [],
                searchUser: '',
                pageNum: 1,
                pageSize: 5,
                total: 0,
                addDialogVisible: false,
                addForm:{username:'',password:'',email:''},
                addFormRules:{
                  username: [{required: true, message: '请输入用户名', trigger: 'blur'},
                              {min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur'}],
                  password: {required: true, message: '请输入密码', trigger: 'blur'},
                  email: [{required: true, message: '请输入邮箱', trigger: 'blur'},
                      {validator: checkEmail, trigger: 'blur'}],

                },
                editDialogVisible: false,
                editForm:{username:'',name:'',email:'',phoneNum:'',demandNum:0,introduction:''},
                editFormRules:{
                    email: [{required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}],
                    phoneNum: [
                        {required:false},
                        {validator: checkPhoneNum, trigger:'blur'}
                    ]

                },

            }
        },
        methods: {
            getUserList() {
                let data = new FormData();
                data.append('currentPage', this.pageNum);
                data.append('size', this.pageSize);
                data.append('username', this.searchUser);
                selectAllUser(data).then((res) => {
                    if (res.code === 200){
                        this.userList = res.data.records;
                        this.total = res.data.total;
                    }

                })
            },
            deleteUser(userId) {
                const confirmResult = this.$confirm(
                    '此操作将永久删除该用户, 是否继续?',
                    '提示',
                    {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(()=>{
                    let data = {};
                    data.userId = userId;
                    deleteUserById(data).then((res) => {
                        if (res.code === 200) {
                            this.$message.success(res.message);
                            this.getUserList();
                        } else {
                            this.$message.error(res.message);
                        }

                    })
                }).catch(() => {
                    this.$message.info('已取消删除');
                });

            },
            handleSizeChange(newSize) {
                this.pageSize = newSize;
                this.getUserList();
            },
            handleCurrentChange(newPage) {
                this.pageNum = newPage;
                this.getUserList();
            },
            changeUserStatus(user) {
                changeUserById(user).then((res) => {
                    if (res.code === 200) {
                        this.$message.success(res.message);
                    } else {
                        this.$message.error(res.message);
                    }
                })
            },
            addUser(){
              this.addDialogVisible = true;
            },
            addDialogClosed(){
                this.$refs.addFormRef.resetFields();
            },
            submitAddUser(){
                this.$refs.addFormRef.validate(valid => {
                    if (!valid) return;
                    addUser(this.addForm).then((res) =>{
                        if (res.code !== 200){
                            this.$message.error(res.message);
                        }
                        this.$message.success(res.message);
                        this.addDialogVisible = false;
                        this.getUserList();
                    })
                })
            },
            showEditDialog(userId){
                this.editDialogVisible = true;
                let data = {};
                data.userId = userId;
                selectUser(data).then((res)=>{
                    this.editForm = res.data;
                })
            },
            editDialogClosed(){
                this.$refs.editFormRef.resetFields();
            },
            changeUser(){
                this.$refs.editFormRef.validate(valid=>{
                    if (!valid) return;
                    changeUserById(this.editForm).then((res)=>{
                        if (res.code !== 200){
                            this.$message.error(res.message);
                        }
                        this.editDialogVisible = false;
                        this.getUserList();
                        this.$message.success(res.message);
                    })
                })
            },
        },
        created() {
            this.getUserList();
        }
    }
</script>

<style lang="less" scoped>
  @import "../../styles/css/global.css";

</style>
